package portal.controller;

import java.io.*;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import beans.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import portal.dao.ScheduleJobDetailDao;
import portal.engine.JobOperator;
import portal.engine.JobQueue;

/**
 * Servlet implementation class AlgorithmServlet
 */
public class JobServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	@Autowired
	private ScheduleJobDetailDao scheduleJobDetailDao;
	private String token;

	public JobServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String operateType = request.getParameter("operateType");
		/**
		 * 从服务器获取token
		 */
		HttpResult tokenResult = JobOperator.getToken(HttpConfig.userName, HttpConfig.passWord);
		if (tokenResult.isResult()) {
			this.token = tokenResult.getMessage();
		}
		//scheduleJobDetailDao = new ScheduleJobDetailDao();
		switch (operateType) {
		case "showAll":
			doShowAll(request, response);
			break;
		case "searchJob":
			searchJob(request, response);
			break;
		case "showLog":
			doShowLog(request, response);
			break;
		case "kill":
			operateJob(request, response, HttpConfig.stopJob);
			break;
		case "peek":
			operateJob(request, response, HttpConfig.peekJob);
			break;
		case "resume":
			operateJob(request, response, HttpConfig.restartJob);
			break;
		case "stop":
			operateJob(request, response, HttpConfig.pauseJob);
			break;
		case "top":
			operateJob(request, response, HttpConfig.topJob);
			break;
		case "bot":
			operateJob(request, response, HttpConfig.botJob);
			break;
		case "delete":
			deleteJob(request, response);
			break;

		default:
			break;
		}
	}

	/**
	 * By黄振 查看并下载日志
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doShowLog(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String jobId = request.getParameter("jobId");
		String fileUrl = JobOperator.queryLogFileUrl(jobId);
		String logFilePath = null;
		// 查询到日志文件地址，进一步去下载文件到本地服务器
		if (fileUrl != null) {
			// 将远端日志文件下载到本地服务器
			logFilePath = JobOperator.downloadLogFile(fileUrl,jobId);

		}
		if (logFilePath != null) {
			String logFold = HttpConfig.socketLogFileUri;
			File file = new File(logFold + logFilePath);
			BufferedReader bufferedReader;
			if (logFilePath.substring(logFilePath.lastIndexOf(".") + 1, logFilePath.length()).equals("log")) {
				bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			} else {
				bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
			}
			String temp = "";
			StringBuffer result = new StringBuffer();
			while ((temp = bufferedReader.readLine()) != null) {
				temp = new String(temp.getBytes(), "utf-8");
				result.append(temp);
			}
			JSONObject resultJson = new JSONObject();
			resultJson.put("preview", result.toString());
			resultJson.put("url", logFilePath);
			response.getWriter().write(resultJson.toString());
		} else {
			response.getWriter().write("error");
		}

	}

	/**
	 * By黄振 获得job实时运行状态
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doShowJobState(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String jobId = request.getParameter("jobId");
		// 暂时不使用2018/9/29
		HttpResultList httpResultList = JobOperator.getScheduleJobFullState(jobId, this.token);
		JSONObject result = JSONObject.fromObject(httpResultList);
		JSONObject json = new JSONObject();
		json.put("resource", result);
		response.getWriter().print(json.toString());
	}

	/**
	 * By黄振 查询全部作业
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@Deprecated
	private void doShowAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("userId");
		Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
		Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
		List<Object> jobs = scheduleJobDetailDao.getJobDetails(userId, onePageCount, currentPage);
		int pageNum = scheduleJobDetailDao.getJobPageNum(onePageCount);
		JSONObject result = new JSONObject();
		JSONObject content = new JSONObject();
		content.put("jobs", JSONArray.fromObject(jobs));
		content.put("pageNum", pageNum);
		result.put("result", content);
		response.getWriter().print(result.toString());
	}

	/**
	 * By 黄振 根据作业名称查询作业
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@Deprecated
	private void searchJob(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		String jobName = request.getParameter("jobName");
		String userId = (String) session.getAttribute("userId");
		Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
		Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
		List<Object> jobList = scheduleJobDetailDao.getJobDetailsByJobName(jobName, onePageCount, currentPage);
		int pageNum = scheduleJobDetailDao.getJobPageNumByJobName(onePageCount, jobName);
		JSONObject result = new JSONObject();
		JSONObject content = new JSONObject();
		content.put("jobDetail", JSONArray.fromObject(jobList));
		content.put("pageNum", pageNum);
		result.put("result", content);
		response.getWriter().print(result.toString());
	}

	/**
	 * By 黄振 根据作业Id删除作业
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void deleteJob(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String jobId = request.getParameter("jobId");
		boolean isDelete = scheduleJobDetailDao.deleteJob(jobId);
		JSONObject result = new JSONObject();
		result.put("result", isDelete);
		response.getWriter().print(result.toString());
	}

	/**
	 * By 黄振 停止/暂停/恢复//置顶/置底作业
	 * 
	 * @param request
	 * @param response
	 * @param operateUrl
	 * @throws IOException
	 */
	private void operateJob(HttpServletRequest request, HttpServletResponse response, String operateUrl)
			throws IOException {

		String jobId = request.getParameter("jobId");
		JSONObject json = new JSONObject();
		String message = null;
		Boolean result = null;

		HttpResult httpResult = JobOperator.operateScheduleJob(operateUrl, jobId, this.token);
		message = httpResult.getMessage();
		result = httpResult.isResult();
		if (result) {
			if (operateUrl.equals(HttpConfig.restartJob)) {
				// 如果重新启动作业成功，将作业添加作业队列
				JobQueue.add(jobId);
			}
			if (operateUrl.equals(HttpConfig.stopJob)) {
				result = JobOperator.updateScheduleJob(jobId, this.token);
				if (!result) {
					message = "数据库更新失败";
				}
			}
		}

		json.put("result", result);
		json.put("resource", message);
		response.getWriter().print(json.toString());

	}

}
